from First.DataAccess import utils
from First import views
import requests

def qudaofenxi(start_date,end_date):
    def hanneihuoqushuju(start_date, end_date):
        access_token, appkey = utils.huoquyonghujiapi()
        method = 'channel/a'
        metrics = 'new_user_count_channel,brand_new_user_count_channel,session_count_channel,user_count_channel,average_session_time_channel'
        url = 'https://openapi.baidu.com/rest/2.0/mtj/svc/app/getDataByKey?access_token={access_token}&key={appkey}&method={method}&start-date={start_date}&end-date={end_date}&metrics={metrics}'.format(
            access_token=access_token, appkey=appkey, method=method, start_date=start_date, end_date=end_date,
            metrics=metrics)
        return request_data(url)

    str1 = hanneihuoqushuju(start_date, end_date)
    # print(str1)
    if 'error_code' in str1:
        utils.gengxinyonghujiapi()
        str1 = hanneihuoqushuju(start_date, end_date)
        if 'error_code' in str1:
            views.hanshurwzanting('rwqudaofenxi')
    if 'error_code' not in str1:
        length = len(str1['result']['items'][0])
        dataqingxi = {}
        dataqingxi['qudaoming'] = []
        dataqingxi['benqudaoxinyonghu'] = []
        dataqingxi['qudaoxinyonghu'] = []
        dataqingxi['qidongcishu'] = []
        dataqingxi['qidongyonghu'] = []
        dataqingxi['pingjunsyshichang'] = []
        for num in range(0, length):
            dataqingxi['qudaoming'].append(str1['result']['items'][0][num][0]['channelName'])
            dataqingxi['benqudaoxinyonghu'].append(int(str1['result']['items'][1][num][0]))
            dataqingxi['qudaoxinyonghu'].append(int(str1['result']['items'][1][num][1]))
            dataqingxi['qidongcishu'].append(int(str1['result']['items'][1][num][2]))
            dataqingxi['qidongyonghu'].append(int(str1['result']['items'][1][num][3]))
            dataqingxi['pingjunsyshichang'].append(int(str1['result']['items'][1][num][4]))
        return dataqingxi


def request_data(url):
    req = requests.get(url, timeout=30)  # 请求连接
    req_jason = req.json()  # 获取数据
    return req_jason